<template>
  <div class="article-manager">
    <div class="i-layout-page-header">
      <PageHeader class="product_tabs" title="产品管理" hidden-breadcrumb>
        <div slot="content">
          <Tabs v-model="artFrom.type" @on-click="onClickTab">
            <TabPane
              :label="item.name + '(' + item.count + ')'"
              :name="item.type.toString()"
              v-for="(item, index) in headeNum"
              :key="index"
            />
          </Tabs>
        </div>
      </PageHeader>
    </div>
    <Alert
      v-if="alertShow"
      banner
      closable
      type="warning"
      class="ivu-mt"
      @on-close="closeAlert"
    >
      <router-link to="/admin/product/add_product/0"
        >您有未完成的产品添加操作，点击此处可继续添加操作？</router-link
      >
    </Alert>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Form
        ref="artFrom"
        :model="artFrom"
        :label-width="labelWidth"
        :label-position="labelPosition"
        @submit.native.prevent
      >
        <Row type="flex" :gutter="24">
          <Col v-bind="grid">
            <FormItem label="产品分类：" label-for="pid">
              <!-- <Select v-model="artFrom.cate_id"  clearable @on-change="userSearchs">
                                <Option v-for="item in treeSelect" :value="item.id" :key="item.id">{{ item.html + item.cate_name }}</Option>
                            </Select> -->
              <Cascader
                :data="data1"
                v-model="value1"
                change-on-select
                @on-change="cascaderSearchs"
              ></Cascader>
            </FormItem>
          </Col>
          <Col v-bind="grid">
            <FormItem label="产品搜索：" label-for="store_name">
              <Input
                search
                enter-button
                placeholder="请输入产品名称,关键字,ID"
                v-model="artFrom.store_name"
                @on-search="userSearchs"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div class="Button">
        <router-link
          v-auth="['product-product-save']"
          :to="'/admin/product/add_product'"
          ><Button type="primary" class="bnt mr15" icon="md-add"
            >添加产品</Button
          ></router-link
        >
        <!-- <Button
          v-auth="['product-crawl-save']"
          type="success"
          class="bnt mr15"
          @click="onCopy"
          >产品采集</Button
        > -->
        <Tooltip content="本页至少选中一项" :disabled="!!formSelection.length">
          <Button
            v-auth="['product-product-product_show']"
            class="bnt mr15"
            :disabled="!formSelection.length"
            @click="onDismount"
            v-show="artFrom.type === '1'"
            >批量下架</Button
          >
        </Tooltip>
        <Tooltip content="本页至少选中一项" :disabled="!!formSelection.length">
          <Button
            v-auth="['product-product-product_show']"
            class="bnt mr15"
            :disabled="!formSelection.length"
            @click="onShelves"
            v-show="artFrom.type === '2'"
            >批量上架</Button
          >
        </Tooltip>
        <Tooltip content="本页至少选中一项" :disabled="!!formSelection.length">
          <Button
            v-auth="['export-storeProduct']"
            class="export"
            icon="ios-share-outline"
            :disabled="!formSelection.length"
            @click="exports"
            >导出</Button
          >
        </Tooltip>
      </div>
      <Table
        ref="table"
        :columns="
          artFrom.type !== '1' && artFrom.type !== '2' ? columns2 : columns
        "
        :data="tableList"
        class="ivu-mt"
        :loading="loading"
        highlight-row
        @on-selection-change="onSelectTab"
        no-data-text="暂无数据"
        no-filtered-data-text="暂无筛选结果"
        @on-select-all="selectAll"
        @on-select-all-cancel="selectAll"
      >
        <template slot-scope="{ row }" slot="id">
          {{ row.id }}
        </template>
        <template slot-scope="{ row }" slot="image">
          <viewer>
            <div class="tabBox_img">
              <img v-lazy="row.image" />
            </div>
          </viewer>
        </template>
        <template slot-scope="{ row, index }" slot="state">
          <i-switch
            v-model="row.is_show"
            :value="row.is_show"
            :true-value="1"
            :false-value="0"
            @on-change="changeSwitch(row)"
            size="large"
          >
            <span slot="open">上架</span>
            <span slot="close">下架</span>
          </i-switch>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <a @click="edit(row)">编辑</a>
          <Divider type="vertical" />
          <router-link :to="{ path: '/admin/product/product_reply/' + row.id }"
            ><a>查看评论</a></router-link
          >
          <Divider type="vertical" />
          <a @click="del(row, '恢复产品', index)" v-if="artFrom.type === '6'"
            >恢复产品</a
          >
          <a @click="del(row, '移入回收站', index)" v-else>移到回收站</a>
        </template>
      </Table>
      <div class="acea-row row-right page">
        <Page
          :total="total"
          :current="artFrom.page"
          show-elevator
          show-total
          @on-change="pageChange"
          :page-size="artFrom.limit"
        />
      </div>
      <attribute
        :attrTemplate="attrTemplate"
        v-on:changeTemplate="changeTemplate"
      ></attribute>
    </Card>
    <!-- 生成淘宝京东表单-->
    <Modal
      v-model="modals"
      :z-index="100"
      class="Box"
      scrollable
      footer-hide
      closable
      title="复制淘宝、天猫、京东、苏宁、1688"
      :mask-closable="false"
      width="1200"
      height="500"
    >
      <tao-bao ref="taobaos" v-if="modals" @on-close="onClose"></tao-bao>
    </Modal>
  </div>
</template>

<script>
import expandRow from "./tableExpand.vue";
import attribute from "./attribute";
import toExcel from "../../../utils/Excel.js";
import { mapState } from "vuex";
import taoBao from "./taoBao";
import {
  getGoodHeade,
  getGoods,
  PostgoodsIsShow,
  treeListApi,
  productShowApi,
  productUnshowApi,
  storeProductApi,
  cascaderListApi,
  productCache,
  cacheDelete,
} from "@/api/product";
import exportExcel from "@/utils/newToExcel.js";

export default {
  name: "product_productList",
  components: { expandRow, attribute, taoBao },
  computed: {
    ...mapState("admin/layout", ["isMobile"]),
    ...mapState("admin/userLevel", ["categoryId"]),
    labelWidth() {
      return this.isMobile ? undefined : 75;
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    },
  },
  data() {
    return {
      template: false,
      modals: false,
      grid: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24,
      },
      artFrom: {
        page: 1,
        limit: 15,
        cate_id: "",
        type: "1",
        store_name: "",
        excel: 0,
      },
      list: [],
      tableList: [],
      headeNum: [],
      treeSelect: [],
      loading: false,
      columns: [
        {
          type: "expand",
          width: 50,
          render: (h, params) => {
            return h(expandRow, {
              props: {
                row: params.row,
              },
            });
          },
        },
        {
          width: 60,
          align: "center",
          renderHeader: (h, params) => {
            return h(
              "div",
              {
                class: {
                  "select-panel": true,
                },
                on: {
                  mouseenter: (e) => {
                    this.display = "block";
                  },
                  mouseleave: (e) => {
                    this.display = "none";
                  },
                },
              },
              [
                h("Checkbox", {
                  props: {
                    value: this.checkBox,
                  },
                  on: {
                    "on-change": (e) => {
                      this.checkBox = e;
                      this.$refs.table.selectAll(this.checkBox);
                      this.isAll = e ? 0 : -1;
                    },
                  },
                }),
                h(
                  "div",
                  {
                    style: {
                      position: "absolute",
                      top: 0,
                      zIndex: 2,
                      display: this.display,
                      width: "80px",
                      height: "100%",
                      padding: "0px 0",
                      borderRadius: "4px",
                      backgroundColor: "#fff",
                      boxShadow: "0 0px 5px rgba(0, 0, 0, 0.2)",
                      transform: "translateX(25%)",
                    },
                  },
                  [
                    h(
                      "div",
                      {
                        class: {
                          "select-item": true,
                          on: this.isAll === 0,
                        },
                        style: {
                          padding: "1px 6px",
                          cursor: "pointer",
                          height: "50%",
                        },
                        on: {
                          click: (e) => {
                            if (this.isAll === 0) {
                              this.isAll = -1;
                              this.checkBox = false;
                              this.$refs.table.selectAll(this.checkBox);
                            } else {
                              this.isAll = 0;
                              if (!this.formSelection.length) {
                                this.checkBox = true;
                                this.$refs.table.selectAll(this.checkBox);
                              }
                            }
                            this.display = "none";
                          },
                        },
                      },
                      "选择当页"
                    ),
                    h(
                      "div",
                      {
                        class: {
                          "select-item": true,
                          on: this.isAll === 1,
                        },
                        style: {
                          padding: "1px 6px",
                          cursor: "pointer",
                          height: "50%",
                        },
                        on: {
                          click: (e) => {
                            if (this.isAll === 1) {
                              this.isAll = -1;
                              this.checkBox = false;
                            } else {
                              this.isAll = 1;
                              this.checkBox = true;
                            }
                            this.$refs.table.selectAll(this.checkBox);
                            this.display = "none";
                          },
                        },
                      },
                      "选择全部"
                    ),
                  ]
                ),
              ]
            );
          },
          render: (h, params) => {
            return h("Checkbox", {
              props: {
                value: params.row.checkBox,
              },
              on: {
                "on-change": (e) => {
                  if (e) {
                    this.formSelection.push(params.row);
                  } else {
                    this.checkBox = false;
                    this.formSelection.forEach((item, index) => {
                      if (item.id === params.row.id) {
                        this.formSelection.splice(index, 1);
                      }
                    });
                  }
                  this.ids = this.formSelection.map((item) => item.id);
                  this.isAll = this.formSelection.length ? 0 : -1;
                  // this.responseData为查询出的结果数据
                  // params.row.checkBox = e;
                  params.row.checkBox = e;
                  this.tableList[params.index].checkBox = e;
                },
              },
              ref: "checkbox",
              refInFor: true,
            });
          },
        },
        {
          title: "产品ID",
          slot: "id",
          width: 80,
        },
        {
          title: "产品图",
          slot: "image",
          minWidth: 80,
        },
        {
          title: "产品名称",
          key: "store_name",
          minWidth: 250,
        },
        {
          title: "产品售价",
          key: "price",
          minWidth: 90,
        },
        {
          title: "销量",
          key: "sales",
          sortable: true,
          minWidth: 90,
        },
        {
          title: "库存",
          key: "stock",
          minWidth: 80,
        },
        {
          title: "排序",
          key: "sort",
          minWidth: 70,
        },
        {
          title: "状态",
          slot: "state",
          width: 100,
          filters: [
            {
              label: "上架",
              value: 1,
            },
            {
              label: "下架",
              value: 0,
            },
          ],
          filterMethod(value, row) {
            return row.is_show === value;
          },
          filterMultiple: false,
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          minWidth: 220,
        },
      ],
      data: [],
      total: 0,
      attrTemplate: false,
      ids: [],
      display: "none",
      formSelection: [],
      selectionCopy: [],
      checkBox: false,
      isAll: -1,
      data1: [],
      value1: [],
      alertShow: false,
      // activeKey:1
    };
  },
  watch: {
    $route() {
      if (this.$route.fullPath === "/admin/product/product_list?type=5") {
        this.getPath();
      }
    },
    formSelection(value) {
      // this.checkBox = value.length === this.tableList.length;
    },
    tableList: {
      deep: true,
      handler(value) {
        value.forEach((item) => {
          this.formSelection.forEach((itm) => {
            if (itm.id === item.id) {
              item.checkBox = true;
            }
          });
        });
        const arr = this.tableList.filter((item) => item.checkBox);
        if (this.tableList.length) {
          this.checkBox = this.tableList.length === arr.length;
        } else {
          this.checkBox = false;
        }
      },
    },
  },
  created() {
    // this.artFrom.type = this.$route.query.key || 1
    // this.columns2 = [...this.columns];
    // if (name !== '1' && name !== '2') {
    //     this.columns2.shift({
    //         type: 'selection',
    //         width: 60,
    //         align: 'center'
    //     })
    // }
    productCache()
      .then((res) => {
        const info = res.data.info;
        if (!Array.isArray(info)) {
          this.alertShow = true;
        }
      })
      .catch((err) => {
        this.$Message.error(err.msg);
      });
  },
  mounted() {
                  console.log(4444444,this.$route.fullPath )

    this.goodHeade();
    this.goodsCategory();
    if (this.$route.fullPath === "/admin/product/product_list?type=5") {
      this.getPath();
    } else {
      this.getDataList();
    }
    // this.getDataList();
  },
  methods: {
    closeAlert() {
      cacheDelete()
        .then((res) => {
          this.$Message.success(res.msg);
        })
        .catch((err) => {
          this.$Message.error(err.msg);
        });
    },
    selectAll(row) {
      if (row.length) {
        this.formSelection = row;
        this.selectionCopy = row;
      }

      this.selectionCopy.forEach((item, index) => {
        item.checkBox = this.checkBox;
        this.$set(this.tableList, index, item);
      });
    },
    getPath() {
      this.columns2 = [...this.columns];
      if (name !== "1" && name !== "2") {
        this.columns2.shift({
          type: "selection",
          width: 60,
          align: "center",
        });
      }
      this.artFrom.page = 1;
      this.artFrom.type = this.$route.query.type.toString();
      this.getDataList();
    },
    // 导出
    // exports() {
    //   let formValidate = this.artFrom;
    //   let data = {};
    //   if (this.isAll === 0) {
    //     data.ids = this.ids.join();
    //   } else if (this.isAll === 1) {
    //     data.cate_id = formValidate.cate_id;
    //     data.type = formValidate.type;
    //     data.store_name = formValidate.store_name;
    //   }
    //   storeProductApi(data)
    //     .then((res) => {
    //       location.href = res.data[0];
    //     })
    //     .catch((res) => {
    //       this.$Message.error(res.msg);
    //     });
    // },
    // 数据导出；
    async exports() {
      let [th, filekey, data, fileName] = [[], [], [], ""];
      let formValidate = this.artFrom;
      let excelData = {};
      if (this.isAll === 0) {
        excelData.ids = this.ids.join();
      } else if (this.isAll === 1) {
        excelData.cate_id = formValidate.cate_id;
        excelData.type = formValidate.type;
        excelData.store_name = formValidate.store_name;
      }
      excelData.page = 1;
      for (let i = 0; i < excelData.page + 1; i++) {
        let lebData = await this.getExcelData(excelData);
        if (!fileName) fileName = lebData.filename;
        if (!filekey.length) {
          filekey = lebData.filekey;
        }
        if (!th.length) th = lebData.header;
        if (lebData.export.length) {
          data = data.concat(lebData.export);
          excelData.page++;
        }
      }
      console.log(5555,data)
      // exportExcel(th, filekey, fileName, data);
    },
    getExcelData(excelData) {
      return new Promise((resolve, reject) => {
        storeProductApi(excelData).then((res) => {
          return resolve(res.data);
        });
      });
    },
    changeTemplate(e) {
      // this.template = e;
    },
    freight() {
      this.$refs.template.isTemplate = true;
    },
    // 批量上架
    onShelves() {
      if (this.ids.length === 0) {
        this.$Message.warning("请选择要上架的产品");
      } else {
        let data = {
          all: this.isAll,
        };
        if (this.isAll === 0) {
          data.ids = this.ids;
        } else if (this.isAll === 1) {
          data.where = {
            cate_id: this.artFrom.cate_id,
            excel: this.artFrom.excel,
            store_name: this.artFrom.store_name,
            type: this.artFrom.type,
          };
        }
        productShowApi(data)
          .then((res) => {
            this.$Message.success(res.msg);
            this.goodHeade();
            this.getDataList();
          })
          .catch((res) => {
            this.$Message.error(res.msg);
          });
      }
    },
    // 批量下架
    onDismount() {
      if (this.ids.length === 0) {
        this.$Message.warning("请选择要下架的产品");
      } else {
        let data = {
          all: this.isAll,
        };
        if (this.isAll === 0) {
          data.ids = this.ids;
        } else if (this.isAll === 1) {
          data.where = {
            cate_id: this.artFrom.cate_id,
            excel: this.artFrom.excel,
            store_name: this.artFrom.store_name,
            type: this.artFrom.type,
          };
        }
        productUnshowApi(data)
          .then((res) => {
            this.$Message.success(res.msg);
            this.goodHeade();
            this.getDataList();
          })
          .catch((res) => {
            this.$Message.error(res.msg);
          });
      }
    },
    // 全选
    onSelectTab(selection) {
      this.formSelection = selection;
      let data = [];
      selection.map((item) => {
        data.push(item.id);
      });
      this.ids = data;
    },
    // 添加淘宝产品成功
    onClose() {
      this.modals = false;
    },
    // 复制淘宝
    onCopy() {
      this.modals = true;
    },
    // tab选择
    onClickTab(name) {
      this.artFrom.type = name;
      this.columns2 = [...this.columns];
      if (name !== "1" && name !== "2") {
        this.columns2.shift({
          type: "selection",
          width: 60,
          align: "center",
        });
      }
      this.checkBox = false;
      this.getDataList();
    },
    // 下拉树
    handleCheckChange(data) {
      let value = "";
      let title = "";
      this.list = [];
      this.artFrom.cate_id = 0;
      data.forEach((item, index) => {
        value += `${item.id},`;
        title += `${item.title},`;
      });
      value = value.substring(0, value.length - 1);
      title = title.substring(0, title.length - 1);
      this.list.push({
        value,
        title,
      });
      this.artFrom.cate_id = value;
      this.getDataList();
    },
    // 获取产品表单头数量
    goodHeade() {
      getGoodHeade()
        .then((res) => {
          this.headeNum = res.data.list;
        })
        .catch((res) => {
          this.$Message.error(res.msg);
        });
    },
    // 产品分类；
    goodsCategory() {
      // treeListApi(1).then(res => {
      //     this.treeSelect = res.data;
      // }).catch(res => {
      //     this.$Message.error(res.msg);
      // })
      cascaderListApi(1)
        .then((res) => {
          this.data1 = res.data;
        })
        .catch((res) => {
          this.$Message.error(res.msg);
        });
    },
    // 产品列表；
    getDataList() {
      this.loading = true;
      this.artFrom.cate_id = this.artFrom.cate_id || "";
      getGoods(this.artFrom)
        .then((res) => {
          let data = res.data;
          this.tableList = data.list.map((item) => {
            if (this.isAll === 1) {
              item.checkBox = true;
            } else {
              item.checkBox = false;
            }
            return item;
          });
          this.total = res.data.count;
          this.loading = false;
        })
        .catch((res) => {
          this.loading = false;
          this.$Message.error(res.msg);
        });
    },
    pageChange(status) {
      this.artFrom.page = status;
      this.getDataList();
      this.$refs.table.clearCurrentRow();
    },
    cascaderSearchs(value, selectedData) {
      this.artFrom.cate_id = value[value.length - 1];
      this.userSearchs();
    },
    // 表格搜索
    userSearchs() {
      this.artFrom.page = 1;
      this.formSelection = [];
      this.getDataList();
    },
    // 上下架
    changeSwitch(row) {
      PostgoodsIsShow(row.id, row.is_show)
        .then((res) => {
          this.$Message.success(res.msg);
          this.goodHeade();
          this.getDataList();
        })
        .catch((res) => {
          this.$Message.error(res.msg);
        });
    },
    // 数据导出；
    exportData: function () {
      let th = [
        "产品名称",
        "产品简介",
        "产品分类",
        "价格",
        "库存",
        "销量",
        "收藏人数",
      ];
      let filterVal = [
        "store_name",
        "store_info",
        "cate_name",
        "price",
        "stock",
        "sales",
        "collect",
      ];
      this.where.page = "nopage";
      getGoods(this.where).then((res) => {
        let data = res.data.map((v) => filterVal.map((k) => v[k]));
        let fileTime = Date.parse(new Date());
        let [fileName, fileType, sheetName] = [
          "商户数据_" + fileTime,
          "xlsx",
          "商户数据",
        ];
        toExcel({ th, data, fileName, fileType, sheetName });
      });
    },
    // 属性弹出；
    attrTap() {
      this.attrTemplate = true;
    },
    changeTemplate(msg) {
      this.attrTemplate = msg;
    },
    // 编辑
    edit(row) {
      this.$router.push({ path: "/admin/product/add_product/" + row.id });
    },
    // 确认
    del(row, tit, num) {
      let delfromData = {
        title: tit,
        num: num,
        url: `product/product/${row.id}`,
        method: "DELETE",
        ids: "",
      };
      this.$modalSure(delfromData)
        .then((res) => {
          this.$Message.success(res.msg);
          this.tableList.splice(num, 1);
          this.goodHeade();
        })
        .catch((res) => {
          this.$Message.error(res.msg);
        });
    },
    // 删除成功
    // submitModel () {
    //     this.tableList.splice(this.delfromData.num, 1);
    //     this.goodHeade();
    // }
    // 排序
    sortChanged(e) {
      this.artFrom[e.key] = e.order;
      this.getDataList();
    },
  },
};
</script>
<style scoped lang="stylus">
/deep/.ivu-modal-mask {
  z-index: 999 !important;
}

/deep/.ivu-modal-wrap {
  z-index: 999 !important;
}

.Box {
  >>> .ivu-modal-body {
    height: 700px;
    overflow: auto;
  }
}

.tabBox_img {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }
}

/deep/.ivu-table-cell-expand-expanded {
  margin-top: -6px;
  margin-right: 33px;
  transition: none;

  .ivu-icon {
    vertical-align: 2px;
  }
}

/deep/.ivu-table-header {
  // overflow visible
}

/deep/.ivu-table th {
  overflow: visible;
}

/deep/.select-item:hover {
  background-color: #f3f3f3;
}

/deep/.select-on {
  display: block;
}

/deep/.select-item.on {
  background: #f3f3f3;
}
</style>
